package cn.com.chengmandian.core.lot;

import cn.com.chengmandian.core.lot.properties.AmqpProperties;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.InvokeThingServiceRequest;
import com.aliyun.iot20180120.models.InvokeThingServiceResponse;
import com.aliyun.tea.TeaModel;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@Slf4j
@ConditionalOnProperty(prefix = "cmd.iot.amqp", name = "enable", havingValue = "true")
@Component
public class InvokeThingService {

    @Autowired
    private AmqpProperties amqpProperties;

    public boolean send(String identifier, String deviceName, String productKey, String json) {
        try {
            Client client = createClient(amqpProperties.getAccessKeyId(), amqpProperties.getAccessKeySecret(), amqpProperties.getEndPoint());
            InvokeThingServiceRequest invokeThingServiceRequest = new InvokeThingServiceRequest()
                    .setProductKey(productKey)
                    .setDeviceName(deviceName)
                    .setIdentifier(identifier)
                    .setIotInstanceId(amqpProperties.getIotInstanceId())
                    .setArgs(json);
            log.info("sendMessage  productKey:{},deviceName:{},identifier:{},json:{}", productKey, deviceName, identifier, json);
            InvokeThingServiceResponse resp = client.invokeThingService(invokeThingServiceRequest);
            log.info(Common.toJSONString(TeaModel.buildMap(resp)));
            return resp.getBody().getSuccess();
        } catch (Exception e) {
            log.error("InvokeThingService 调用异常，", e);
        }
        return false;
    }

    /**
     * 使用AK&SK初始化账号Client
     */
    public Client createClient(String accessKeyId, String accessKeySecret, String endPoint) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = endPoint;
        return new Client(config);
    }
}
